iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
0

Why requests.get works

來看看README內的給我們的範例

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code

Why requests.get works?

到目前為止的理解是因為兩個因素

  1. When a regular package is imported, this __init__.py file is implicitly executed
  2. requests的__init__.py內的宣告
from .api import request, get, head, post, patch, put, delete, options

感覺起來,可以把對外的使用介面,例如: get, post, session...等宣告在__init__.py內,方便其他引用該package的人使用。

requests.api module

定義了HTTP Method: get, options, head, post, put, patch, delete

def get(url, params=None, **kwargs):
    r"""Sends a GET request.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

說明包含:param, :return, :rtype
可以知道requests核心有兩個主要的物件: Request, Response
在文件中看起來的呈現

但其實這7個function都是wrapper function,最後都會使用的function是request
核心是sessions模組內的Session物件

def request(method, ur, **kwargs):
    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)

可以帶入的參數種類非常多,整理docstring的內容如下

HTTP docstrings
params query string (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:Request.
data body (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:Request.
json body (optional) A JSON serializable Python object to send in the body of the :class:Request.
headers Headers (optional) Dictionary of HTTP Headers to send with the :class:Request.
cookies (optional) Dict or CookieJar object to send with the :class:Request.
files (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload.file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.
auth Headers (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
timeout (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:(connect timeout, read timeout) <timeouts> tuple.
allow_redirects (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True.
proxies (optional) Dictionary mapping protocol to the URL of the proxy.
verify (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to True.
stream (optional) if False, the response content will be immediately downloaded.
cert (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.

有些概念需要再釐清

  • CookieJar
  • files
  • allow_redirects
  • proxies
  • stream
  • verify and cert

參考


上一篇
Day5-__init__.py
下一篇
Day7-Session-constructor
系列文
Why it works: python requests and urllib330
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言